from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.mixins import ListModelMixin
from goods.models import SKU
from goods.serializers import SKUSerializer, SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet


# GET /skus/search/?text=<搜索关键字>
class SKUSearchViewSet(HaystackViewSet):
    # 指定索引类对应模型类
    index_models = [SKU]

    # 指定索引结果所使用的序列化器类
    # 搜索结果中的每个对象都包含两个字段
    # text: 索引字段的内容
    # object：从数据库中搜索出的模型类(此处是SKU模型对象)
    serializer_class = SKUIndexSerializer


# GET /categories/(?P<category_id>\d+)/skus/
class CategoriesSKUsView(ListAPIView):
    serializer_class = SKUSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        query_set = SKU.objects.filter(category_id=category_id)
        return query_set

    # 排序
    filter_backends = [OrderingFilter]
    #指定排序字段
    ordering_fields = ('create_time', 'price', 'sales')

    # def get(self, request, category_id):
    #
    #     # 根据分类编号查询商品
    #     skus = self.get_queryset()  # 查询集
    #
    #     # 使用指定的序列化器序列化并返回
    #     serializer = self.get_serializer(skus, many=True)
    #
    #     return Response(serializer.data)
